<template>
  <Layout style="height: 100%" class="main">
    <Sider hide-trigger collapsible :width="256" :collapsed-width="64" v-model="collapsed" class="left-sider"
           :style="{overflow: 'hidden'}">
      <side-menu accordion ref="sideMenu" :active-name="$route.name" :collapsed="collapsed" @on-select="turnToPage"
                 :menu-list="menuList">
        <!-- 需要放在菜单上面的内容，如Logo，写在side-menu标签内部，如下 -->
        <div class="logo-con">
          <div v-show="!collapsed" class="logo_ttile">智慧街道</div>
          <img v-show="collapsed" src="../../assets/images/logo_old.png" key="min-logo"/>
        </div>
      </side-menu>
    </Sider>
    <Layout style="overflow: hidden;" id="main">
      <Header class="header-con">
        <header-bar :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :user-avator="userAvator" :user-name="userName"/>
          <!--<language @on-lang-change="setLocal" style="margin-right: 10px;" :lang="local"/>
          <fullscreen v-model="isFullscreen" style="margin-right: 10px;"/>-->
          <div class="message-div" @click="toMessagePage()" title="消息中心">
            <Icon type="md-notifications"/>
          </div>
          <div class="message-div" @click="toCollectionPage()" title="我的收藏">
            <Icon type="md-cube"/>
          </div>
        </header-bar>
      </Header>
      <Content class="main-content-con">
        <Layout class="main-layout-con">
          <div class="tag-nav-wrapper">
            <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag"/>
          </div>
          <Content class="content-wrapper">
            <keep-alive :include="cacheList">
              <router-view/>
            </keep-alive>
          </Content>
        </Layout>
      </Content>
      <Content class="main-bottom-con">
        <div class="main-bottom-con">
          <div class="main-bottom">
            <a href="http://sd.jnaw.top" target="_blank" class="html-button">
              ©2018 AllView CWBU All Rights Reserved. v{{ version }}
            </a>
          </div>
        </div>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
  import SideMenu from './components/side-menu'
  import HeaderBar from './components/header-bar'
  import TagsNav from './components/tags-nav'
  import User from './components/user'
  import Fullscreen from './components/fullscreen'
  import Language from './components/language'
  import {mapMutations, mapActions} from 'vuex'
  import {getNewTagList, getNextRoute, routeEqual} from '@/libs/util'
  import minLogo from '@/assets/images/logo-min.jpg'
  import maxLogo from '@/assets/images/logo.jpg'
  import './main.less'
  import Cookies from 'js-cookie';
  import util from '../../libs/util';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import Nim from '../../libs/mod.nim';
  import IndexDB from '../../libs/mod.indexDB';
  export default {
    name: 'Main',
    components: {
      SideMenu,
      HeaderBar,
      Language,
      TagsNav,
      Fullscreen,
      User
    },
    data () {
      return {
        collapsed: false,
        minLogo,
        maxLogo,
        isFullscreen: false,
        version: util.version,
        uid: '',
        username: '',
      }
    },
    computed: {
      tagNavList () {
        return this.$store.state.app.tagNavList
      },
      tagRouter () {
        return this.$store.state.app.tagRouter
      },
      userAvator () {
        return Cookies.get('avatorImgPath');
      },
      userName () {
        return Cookies.get('userName');
      },
      cacheList () {
        return this.tagNavList.length ? this.tagNavList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name) : []
      },
      menuList () {
        return this.$store.getters.menuList
      },
      local () {
        return this.$store.state.app.local
      }
    },
    watch: {
      '$route' (newRoute) {
        this.setBreadCrumb(newRoute.matched)
        this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      }
    },
    created () {
      var _this = this;
      _this.getLocalDB();
      _this.login();
    },
    mounted () {
      /**
       * @description 初始化设置面包屑导航和标签导航
       */
      this.setTagNavList()
      this.addTag({
        route: this.$store.state.app.homeRoute
      })
      this.setBreadCrumb(this.$route.matched)
      // 设置初始语言
      this.setLocal(this.$i18n.locale)

    },
    methods: {
      ...mapMutations([
        'setBreadCrumb',
        'setTagNavList',
        'addTag',
        'setLocal'
      ]),
      ...mapActions([
        'handleLogin'
      ]),
      turnToPage (route) {
        let {name, params, query} = {}
        if (typeof route === 'string') name = route
        else {
          name = route.name
          params = route.params
          query = route.query
        }
        if (name.indexOf('isTurnByHref_') > -1) {
          window.open(name.split('_')[1])
          return
        }
        this.$router.push({
          name,
          params,
          query
        })
      },
      handleCollapsedChange (state) {
        this.collapsed = state
      },
      handleCloseTag (res, type, route) {
        let openName = ''
        if (type === 'all') {
          this.turnToPage('home')
          openName = 'home'
        } else if (routeEqual(this.$route, route)) {
          if (type === 'others') {
            openName = route.name
          } else {
            const nextRoute = getNextRoute(this.tagNavList, route)
            this.$router.push(nextRoute)
            openName = nextRoute.name
          }
        }
        this.setTagNavList(res)
        this.$refs.sideMenu.updateOpenName(openName)
      },
      handleClick (item) {
        this.turnToPage(item)
      },
      getAlluser: function () {
        var _this = this;
        var data = {
          departments: [0]
        };
        var params = {
          url: '/user/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var users = _data || [];
            var data_usersObj = {};
            for (var tem in users) {
              var username = users[tem].username;
              var id = users[tem].id;
              var name = users[tem].name;
              var avatar = '/vendors/images/person.png';
              if (users[tem].avatar.thumb) {
                avatar = users[tem].avatar.thumb;
              }
              if (!data_usersObj[username]) {
                data_usersObj[username] = {
                  id: '',
                  no: username,
                  name: '',
                  image: ''
                };
              }
              data_usersObj[username].id = id;
              data_usersObj[username].name = name;
              data_usersObj[username].image = avatar;
            }
            Nim.setUsersObj(data_usersObj);
            _this.getMyTeams();// 取我的群组

          } else {
            _this.$Message.error('查询用户信息失败!');
          }
        }
      },
      getMyTeams: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
        };
        var params = {
          url: '/chat/group/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data;
            var data_usersObj = Nim.getUsersObj();
            var groups = _data;
            for (var k in groups) {
              var id = groups[k].id;
              var no = groups[k].no;
              var name = groups[k].name;
              var is_top = groups[k].pin;
              var mute_team = groups[k].mute;
              if (!data_usersObj[no]) {
                data_usersObj[no] = {
                  id: '',
                  no: no,
                  name: '',
                  image: ''
                };
              }
              data_usersObj[no].id = id;
              data_usersObj[no].name = name;
            }
            Nim.setUsersObj(data_usersObj);
            console.log('data_usersObj team:', data_usersObj);
          } else {
            _this.$Message.error('查询群组信息失败!');
          }
        }
      },
      getLocalDB: function () {
        var _this = this;
        IndexDB.indexedDB_get(Util.toJson(localStorage.getItem('userInfo')).username, 'Nimdata', function (_data) {
          if (_data.code == 0) {
            var str = _data.data.data || '';
            if (str != '') {
              var dataObj = JSON.parse(str);
              Nim.setNimdata(dataObj);
              console.log('获取数据：', dataObj);
            }
          }
          _this.getAlluser();
        });
      },
      login: function () {
        var _this = this;
        var login_mobile = Utils.getCookie('login_mobile');
        var login_password = Utils.getCookie('login_password');
        var mobile = '';
        var password = '';
        if (login_mobile && login_password) {
          login_password = Utils.uncompile(login_password);//解密
          mobile = login_mobile;
          password = login_password;
        }
        var data = {
          mobile: mobile,
          password: password
        };
        var params = {
          url: '/user/login',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            var nim_username = data.username;
            var nim_token = data.nim_token;
            _this.uid = data.id;
            _this.username = data.username;
            console.log('nim_username', nim_username);
            console.log('nim_token', nim_token);
            if (nim_username && nim_token) {
              Nim.nim_login(_this, nim_username, nim_token);
            } else {
              _this.$Message.error('IM未登录!');
            }
            _this.getUserInfoFun();
          } else {
            _this.$Message.error('登录超时，请重新登录!');
            // 退出登录
            _this.loginOut();
            Nim.loginOutNimdata();
            _this.$store.commit('logout', _this);
            _this.$store.commit('clearOpenedSubmenu');
            _this.$router.push({
              name: 'login'
            });
          }
        }
      },
      loginOut: function () {
        var _this = this;
        setTimeout(function () {
          var data = {};
          var params = {
            url: '/user/logout',
            type: Util.method.post,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              console.log('退出成功');
            } else {

            }
          }
        }, 1000);
      },
      getUserInfoFun: function () {
        var _this = this;
        var data = {
          id: _this.uid,
          username: _this.username,
        };
        var params = {
          url: '/user/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || {};
            localStorage.setItem('userInfo', Util.toStr(_data));
            var userName = _data.name;
            var username = _data.username;
            var mobile = _data.mobile;
            var avatar = _data.avatar;
            var thumb = avatar.thumb ? avatar.thumb : '';
            Cookies.set('token', _data.id);
            Cookies.set('avatorImgPath', thumb);
            Cookies.set('userName', userName);
            _this.$store.state.user.avatorImgPath = thumb;
            _this.$store.state.user.userName = userName;
          } else {
            _this.$Message.error('查询用户信息失败!');
          }
        }
      },
      // 消息
      toMessagePage: function () {
        this.$router.push({
          name: 'localMessage_index'
        })
      },
      // 收藏
      toCollectionPage: function () {
        this.$router.push({
          name: 'collection'
        })
      },
    }
  }
</script>
